package channel

import (
	"log"

	"bcb-cc-observ/pkg/models"

	ledgerApi "github.com/hyperledger/fabric-sdk-go/pkg/client/ledger"
)

func GetSummaryInfo(client *ledgerApi.Client, channelid string) (*models.F_CHL_Summary_Info, error) {
	var summary *models.F_CHL_Summary_Info

	summary = new(models.F_CHL_Summary_Info)
	info, err := client.QueryInfo()
	if err != nil {
		log.Fatalf("-X-> 查询区块链概况失败: %v\n", err)
		return nil, err
	}

	summary.ChannelId = channelid
	summary.BlockHeight = int(info.BCI.Height)
	return summary, nil
}

func GetTxCount(client *ledgerApi.Client, blockNumber int) (int, error) {
	var n int

	// 根据区块查询交易
	block, err := client.QueryBlock(uint64(blockNumber))
	if err != nil {
		log.Fatalf("-X-> 查询区块失败: %v\n", err)
		return n, err
	}

	n = len(block.Data.Data)
	//fmt.Printf("  |---> 区块[%d]交易个数:  %d\n", blockNumber, n)

	return n, nil
}

func GetTotalTxCount(client *ledgerApi.Client, height int) (int, error) {
	var n int

	count := height - 1
	for i := 0; i <= count; i++ {
		txcount, _ := GetTxCount(client, i)
		n += txcount
	}

	return n, nil
}
